/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.io.BufferedWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import android.app.Service;
import android.util.Log;

/**
 * Action for getting the compose new message html page
 */
public class HttpActionNewMessage {

  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + HttpActionNewMessage.class.getSimpleName();


  /**
   * @param values
   * @param writer
   * @param service the context/service
   * @throws Exception
   */
  public static void process(Service service, Map<String, String> values, BufferedWriter writer)
    throws Exception {
    writer
      .write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\r\nhttp://www.w3.org/TR/html4/strict.dtd>\r\n<html><head>"
        + "<link rel=\"stylesheet\" href=\"/style.css\" type=\"text/css\" media=\"screen\" />"
        + "<META HTTP-EQUIV=\"content-type\" CONTENT=\"text/html; charset=utf-8\"></head><body  bgcolor=\"#DDDDDD\">");
    String destinations = values.get("empf");
    String text = values.get("text");
    String type = values.get("type");
    boolean saveAsDraft = "draft".equals(type);

    if (null != destinations && null != text) {
      if (!"".equals(destinations) && !"".equals(text)) {
        List<String> list = new ArrayList<String>();
        List<String> usedTokens = new ArrayList<String>();
        List<String> skippedTokens = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(destinations, ";,");

        while (tokenizer.hasMoreElements()) {
          String token = tokenizer.nextToken().trim();
          String number = null;
          if (token.contains("[") && token.contains("]")) {
            number = token.substring(token.indexOf('[') + 1, token.indexOf(']')).trim();
            Log.d(LOGTAG, "Will send to: " + number);
          } else if (token.contains("[") || token.contains("]")) {
            skippedTokens.add(token);
            Log.e(LOGTAG, "skip number " + token);
          } else {
            number = token.trim();
            number = number.replace("+", "00");
            number = number.replace("-", "");
            number = number.replace("/", "");
            number = number.replace("*", "");
            number = number.replace("#", "");
            number = number.replace("p", "");
            number = number.replace("w", "");
            try {
              Long.parseLong(number);
              number = token.replace("+", "00");
              Log.d(LOGTAG, "will send to: " + number);
            } catch (Exception e) {
              Log.w(LOGTAG, "invalid number", e);
              skippedTokens.add(token);
              number = null;
            }
          }
          if (null != number) {
            list.add(number);
            usedTokens.add(token);
          }
        }

        if (!usedTokens.isEmpty()) {

          String[] to = list.toArray(new String[] {});
          int[] threadIds = null;
          if (saveAsDraft) {
            threadIds = MessageHelper.saveDraft(service, to, text);
          } else {
            threadIds = MessageHelper.sendSMS(service, to, text, 0);
          }

          writer.write("<h5>" + service.getResources().getString(R.string.newmessage_sendsuccess) + "</h5>");
          writer.write("<ul>");
          for (int i = 0; i < usedTokens.size(); i++) {
            if (threadIds[i] != 0) {
              writer.write("<li>" + usedTokens.get(i) + " [Thread: " + threadIds[i] + "]</li>");
            } else {
              skippedTokens.add(usedTokens.get(i));
            }
          }
          writer.write("</ul>");
        }
        if (!skippedTokens.isEmpty()) {

          writer.write("<h5>" + service.getResources().getString(R.string.newmessage_sendfailed) + "</h5>");
          writer.write("<ul>");
          for (int i = 0; i < skippedTokens.size(); i++) {
            writer.write("<li>" + skippedTokens.get(i) + "</li>");
          }
          writer.write("</ul>");
        }
      }
    } else {
      Log.w(LOGTAG, "Text oder empfaenger fehlen");
    }

    Util.writeScript(service, writer, false);

    writer
      .write("<div id=\"r3\" style=\"position: fixed; top:0; right:0; height: 18px; width: 90px; background-color: #CCCCCC; text-align: right; \">"
        + "<small><a href=\"/newmessage?\">"
        + service.getResources().getString(R.string.newmessage_reset)
        + "</a></small></div>");

    writeForm(service, writer);

    writer.write("</body></html>");
  }


  /**
   * @param writer
   */
  private static void writeForm(Service service, BufferedWriter writer) throws Exception {
    writer.write("<form name=\"sendform\" method=\"GET\" action=\"/newmessage\">");
    writer.write("<table border=0 hspacing=0 vspacing=0>");
    if (!MainActivity.DONATE_VERSION) {
      writer.write("<tr><td>" + service.getResources().getString(R.string.donate_long_sms_support)
        + "</td></tr>");
    }
    writer.write("<tr><td colspan=\"2\"><b>" + service.getResources().getString(R.string.thread_recipient)
      + ":</b>&nbsp;&nbsp;" + service.getResources().getString(R.string.newmessage_select_ab)
      + " <a href=\"/\" onClick=\"promptNumber(); return false;\">"
      + service.getResources().getString(R.string.newmessage_select_free) + "</a></td></tr>");
    writer
      .write("<tr><td width=\"400\" id=\"empf\"></td><td width=\"120\" align=\"left\"><span id=\"leftchars\" name=\"leftchars\">160"
        + "</span>/<span id=\"smscount\" name=\"smscount\">1</span> (<span id=\"leftTotal\" name=\"leftTotal\">"
        + Util.MAX_SMS_CHARS + "</span>)</td></tr><tr><td colspan=2>");
    writer.write("<textarea onkeyup=\"updateCharCounter();\" cols=\"70\" rows=\"5\" name=\"text\">");
    writer.write("</textarea><br/>");
    writer.write("<input type=\"hidden\" name=\"empf\" value=\"\"/>");
    writer.write("<input type=\"hidden\" name=\"type\" value=\"\"/>");
    writer
      .write("<input onClick=\"document.forms[0].type.value='send'; return setToField() && checkContent();\" type=\"submit\" value=\""
        + service.getResources().getString(R.string.thread_action_send) + "\"/>");
    writer
      .write("<input onClick=\"document.forms[0].type.value='draft'; if (setToField() && checkContent()) document.forms[0].submit();\" type=\"button\" value=\""
        + service.getResources().getString(R.string.thread_save_draft) + "\"/>");
    writer.write("</td></tr></table></form>");
  }
}